package org.tuo.aop;

import org.apache.commons.lang.StringUtils;
import org.fhawk.tinyspring.aop.annotation.Aspect;
import org.fhawk.tinyspring.aop.proxy.Proxy;
import org.fhawk.tinyspring.mvc.annotation.Requset;
import org.fhawk.tinyspring.mvc.bean.Requester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;

@Aspect(pkg = "org.tuo.controller")
public class ControllerAspect implements Proxy {
    private Logger logger = LoggerFactory.getLogger(serviceAspect.class);
    ThreadLocal<LocalDateTime> local = new ThreadLocal<>();

    @Override
    public void doBefore(Method method) {
        local.set(LocalDateTime.now());
        logger.info("=====controller开始=====");
    }

    @Override
    public void doAfter(Method method) {
        logger.info("=====controller结束=====");
    }

    @Override
    public void doFinally(Method method) {
        Requester requester = new Requester();
        Requset requset = method.getAnnotation(Requset.class);
        if (Objects.nonNull(requset)) {
            requester.setMethod(requset.method().value());
            if (StringUtils.isEmpty(requset.value())) {
                requester.setPath("/"+method.getName());
            } else {
                requester.setPath(requset.value());
            }
        }
        logger.debug("接口:{} 处理时间为{}毫秒", requester, Duration.between(local.get(), LocalDateTime.now()).toMillis());
        logger.info("=====controller资源回收=====");
    }

    @Override
    public void doThrowable(Method method, Throwable e) {
        logger.error("=====controller异常=====", e);
    }
}
